home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Technotools
/
Technotools (Chestnut CD-ROM)(1993).ISO
/
lang_ai
/
match
/
match.lsp
Wrap
Lisp/Scheme
|
1990-04-14
|
2KB
|
74 lines
;; File: match.lsp
;; Author: Paul L. Bergstein
;; Common Lisp pattern matching functions
;; Variables in patterns start with '?'
;; ?* matches anything without binding (wildcard variable)
;;---------------------------------------------------------------
;; Function MATCH
;;
;; Usage: (match <<pattern>> <<data>>)
;;
;; Arguments:
;; pattern -- an s-exp possibly containing variables
;; data -- an s-exp which must not contain variables
;;
;; Returns:
;; If successful -- a list of variable bindings (possibly nil)
;; If the pattern and data don't match -- 'fail
;;---------------------------------------------------------------
(defun match (p d &optional bindings)
(cond ((var-p p)
(match-variable p d bindings))
((and (atom p) (atom d))
(match-atoms p d bindings))
((and (listp p) (listp d))
(match-lists p d bindings))
(t 'fail)))
(defun var-p (x)
(cond ((null x) nil)
((symbolp x) (char= (char (symbol-name x) 0) #\?))
(t nil)))
(defun add-binding (var datum bindings)
(if (eq '?* var) bindings
(cons (list var datum) bindings)))
(defun find-binding (var binding)
(unless (eq '?* var)
(assoc var binding)))
(defun get-value (binding)
(cadr binding))
(defun match-atoms (p d bindings)
(if (eql p d)
bindings
'fail))
(defun match-variable (p d bindings)
(let ((binding (find-binding p bindings)))
(if binding
(match (get-value binding) d bindings)
(add-binding p d bindings))))
(defun match-lists (p d bindings)
(let ((result (match (car p) (car d) bindings)))
(if (eq 'fail result)
'fail
(match (cdr p) (cdr d) result))))